<template>
  <div class="app-container">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="logo">
        <el-icon size="24"><Medal /></el-icon>
        运动会管理系统
      </div>
      <div class="flex-grow"></div>
      <div class="user-info">
        <el-dropdown trigger="click">
          <div class="user-avatar">
            <el-avatar :size="40" :src="avatarUrl" icon="UserFilled"></el-avatar>
            <span class="username">{{ currentUser?.realName || '管理员' }}</span>
            <el-icon><ArrowDown /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="handleLogout">
                <el-icon><SwitchButton /></el-icon>
                退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </header>

    <!-- 左侧导航栏 -->
    <nav class="sidebar">
      <div class="menu-item" :class="{ active: $route.path === '/admin' }" @click="navigateTo('/admin')">
        <el-icon><Monitor /></el-icon>
        <span>系统管理</span>
      </div>
      <div class="menu-item" :class="{ active: $route.path === '/admin/users' }" @click="navigateTo('/admin/users')">
        <el-icon><User /></el-icon>
        <span>用户管理</span>
      </div>
      <div class="menu-item" :class="{ active: $route.path === '/admin/projects' }" @click="navigateTo('/admin/projects')">
        <el-icon><List /></el-icon>
        <span>项目管理</span>
      </div>
      <div class="menu-item active">
        <el-icon><Document /></el-icon>
        <span>报名管理</span>
      </div>
      <div class="menu-item" :class="{ active: $route.path === '/admin/schedule' }" @click="navigateTo('/admin/schedule')">
        <el-icon><Calendar /></el-icon>
        <span>赛程管理</span>
      </div>
      <div class="menu-item" :class="{ active: $route.path === '/admin/judges' }" @click="navigateTo('/admin/judges')">
        <el-icon><Bell /></el-icon>
        <span>裁判分配</span>
      </div>
    </nav>

    <!-- 主要内容 -->
    <main class="content">
      <!-- 页面标题和操作按钮 -->
      <div class="page-header">
        <div class="page-title">
          <h1>报名管理</h1>
          <p class="page-desc">管理学生报名信息、审核报名申请、统计报名数据</p>
        </div>
        <div class="header-actions">
          <el-button type="success" @click="handleExport" :loading="exportLoading">
            <el-icon><Download /></el-icon> 导出数据
          </el-button>
          <el-button type="primary" @click="showEnrollmentSettings = true">
            <el-icon><Setting /></el-icon> 报名设置
          </el-button>
          <el-button type="warning" @click="checkConflicts">
            <el-icon><Warning /></el-icon> 冲突检测
          </el-button>
        </div>
      </div>

      <!-- 数据可视化卡片 -->
      <el-row :gutter="20" class="stats-row">
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stats-card" shadow="hover">
            <div class="stats-content">
              <div class="stats-number">{{ enrollmentStats.total }}</div>
              <div class="stats-label">总报名数</div>
            </div>
            <el-icon class="stats-icon" color="#409EFF"><Document /></el-icon>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stats-card" shadow="hover">
            <div class="stats-content">
              <div class="stats-number">{{ enrollmentStats.pending }}</div>
              <div class="stats-label">待审核</div>
            </div>
            <el-icon class="stats-icon" color="#E6A23C"><Clock /></el-icon>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stats-card" shadow="hover">
            <div class="stats-content">
              <div class="stats-number">{{ enrollmentStats.approved }}</div>
              <div class="stats-label">已通过</div>
            </div>
            <el-icon class="stats-icon" color="#67C23A"><CircleCheck /></el-icon>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stats-card" shadow="hover">
            <div class="stats-content">
              <div class="stats-number">{{ enrollmentStats.rejected }}</div>
              <div class="stats-label">已驳回</div>
            </div>
            <el-icon class="stats-icon" color="#F56C6C"><CircleClose /></el-icon>
          </el-card>
        </el-col>
      </el-row>

      <!-- 数据可视化图表 -->
      <el-row :gutter="20" class="chart-row">
        <el-col :xs="24" :md="12">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>报名状态分布</span>
                <el-button-group>
                  <el-button
                    :size="chartSize"
                    @click="refreshChart('status')"
                    :loading="chartLoading.status">
                    <el-icon><Refresh /></el-icon>
                  </el-button>
                </el-button-group>
              </div>
            </template>
            <div ref="statusChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
        <el-col :xs="24" :md="12">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>院系报名分布</span>
                <el-button-group>
                  <el-button
                    :size="chartSize"
                    @click="refreshChart('college')"
                    :loading="chartLoading.college">
                    <el-icon><Refresh /></el-icon>
                  </el-button>
                </el-button-group>
              </div>
            </template>
            <div ref="collegeChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 搜索和筛选区域 -->
      <el-card class="search-card" shadow="hover">
        <el-form :model="searchForm" inline>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-form-item label="学生姓名">
                <el-input
                  v-model="searchForm.realName"
                  placeholder="请输入学生姓名"
                  clearable
                  :prefix-icon="Search"
                  @keyup.enter="handleSearch">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-form-item label="项目名称">
                <el-input
                  v-model="searchForm.projectName"
                  placeholder="请输入项目名称"
                  clearable
                  :prefix-icon="Search"
                  @keyup.enter="handleSearch">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-form-item label="报名状态">
                <el-select
                  v-model="searchForm.status"
                  placeholder="请选择报名状态"
                  clearable
                  style="width: 100%">
                  <el-option
                    v-for="status in enrollmentStatuses"
                    :key="status"
                    :label="status"
                    :value="status">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-form-item label="院系">
                <el-select
                  v-model="searchForm.college"
                  placeholder="请选择院系"
                  clearable
                  style="width: 100%"
                  filterable>
                  <el-option
                    v-for="college in collegeOptions"
                    :key="college"
                    :label="college"
                    :value="college">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-form-item label="班级">
                <el-input
                  v-model="searchForm.className"
                  placeholder="请输入班级"
                  clearable
                  :prefix-icon="Search"
                  @keyup.enter="handleSearch">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-form-item label="项目类型">
                <el-select
                  v-model="searchForm.projectType"
                  placeholder="请选择项目类型"
                  clearable
                  style="width: 100%">
                  <el-option
                    v-for="type in projectTypes"
                    :key="type"
                    :label="type"
                    :value="type">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-form-item label="报名时间">
                <el-date-picker
                  v-model="searchForm.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-form-item>
                <el-button type="primary" @click="handleSearch" :loading="loading">
                  <el-icon><Search /></el-icon> 搜索
                </el-button>
                <el-button @click="handleReset">
                  <el-icon><Refresh /></el-icon> 重置
                </el-button>
                <el-button type="info" @click="toggleAdvancedSearch">
                  <el-icon><Operation /></el-icon> {{ showAdvancedSearch ? '收起' : '高级' }}
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 高级搜索区域 -->
          <el-collapse-transition>
            <div v-show="showAdvancedSearch" class="advanced-search">
              <el-divider content-position="left">高级搜索</el-divider>
              <el-row :gutter="20">
                <el-col :xs="24" :sm="12" :md="8" :lg="6">
                  <el-form-item label="性别">
                    <el-select
                      v-model="searchForm.gender"
                      placeholder="请选择性别"
                      clearable
                      style="width: 100%">
                      <el-option label="男" value="男"></el-option>
                      <el-option label="女" value="女"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6">
                  <el-form-item label="年级">
                    <el-select
                      v-model="searchForm.grade"
                      placeholder="请选择年级"
                      clearable
                      style="width: 100%">
                      <el-option
                        v-for="grade in gradeOptions"
                        :key="grade"
                        :label="grade"
                        :value="grade">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6">
                  <el-form-item label="审核人">
                    <el-input
                      v-model="searchForm.auditor"
                      placeholder="请输入审核人"
                      clearable
                      :prefix-icon="UserFilled"
                      @keyup.enter="handleSearch">
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6">
                  <el-form-item label="是否有冲突">
                    <el-select
                      v-model="searchForm.hasConflict"
                      placeholder="请选择"
                      clearable
                      style="width: 100%">
                      <el-option label="是" value="true"></el-option>
                      <el-option label="否" value="false"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-collapse-transition>
        </el-form>
      </el-card>

      <!-- 报名列表表格 -->
      <el-card class="table-card" shadow="hover">
        <!-- 表格工具栏 -->
        <div class="table-toolbar">
          <div class="table-info">
            <span class="table-title">报名列表</span>
            <el-tag type="info" size="small">共 {{ pagination.total }} 条记录</el-tag>
          </div>
          <div class="table-actions">
            <div class="view-switch">
              <el-radio-group v-model="viewMode" size="small">
                <el-radio-button label="table">
                  <el-icon><Grid /></el-icon> 表格视图
                </el-radio-button>
                <el-radio-button label="card">
                  <el-icon><List /></el-icon> 卡片视图
                </el-radio-button>
              </el-radio-group>
            </div>
            <el-button-group>
              <el-button
                :size="tableSize"
                @click="tableSize = 'large'"
                :class="{ 'is-active': tableSize === 'large' }">
                大
              </el-button>
              <el-button
                :size="tableSize"
                @click="tableSize = 'default'"
                :class="{ 'is-active': tableSize === 'default' }">
                中
              </el-button>
              <el-button
                :size="tableSize"
                @click="tableSize = 'small'"
                :class="{ 'is-active': tableSize === 'small' }">
                小
              </el-button>
            </el-button-group>
            <el-button
              :icon="RefreshRight"
              @click="fetchEnrollments"
              :loading="loading"
              circle>
            </el-button>
          </div>
        </div>

        <!-- 表格视图 -->
        <div v-show="viewMode === 'table'" class="table-view">
          <el-table
            :data="enrollmentList"
            v-loading="loading"
            :height="tableHeight"
            stripe
            border
            :size="tableSize"
            @selection-change="handleSelectionChange"
            @sort-change="handleSortChange"
            style="width: 100%">
            <el-table-column type="selection" width="55" align="center" fixed="left"></el-table-column>
            <el-table-column prop="id" label="ID" width="80" align="center" sortable="custom"></el-table-column>
            <el-table-column label="学生信息" min-width="180" show-overflow-tooltip>
              <template #default="{ row }">
                <div class="user-info">
                  <div class="user-name">{{ row.user?.realName || '-' }}</div>
                  <div class="user-details">
                    <el-tag size="small" type="info">{{ row.user?.className || '-' }}</el-tag>
                    <el-tag size="small" type="primary">{{ row.user?.college || '-' }}</el-tag>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="项目信息" min-width="200" show-overflow-tooltip>
              <template #default="{ row }">
                <div class="project-info">
                  <div class="project-name">{{ row.project?.name || '-' }}</div>
                  <div class="project-details">
                    <el-tag size="small" :type="getProjectTypeTagType(row.project?.type)">
                      {{ row.project?.type || '-' }}
                    </el-tag>
                    <el-tag size="small" :type="getGenderTagType(row.project?.genderLimit)">
                      {{ getGenderLimitText(row.project?.genderLimit) }}
                    </el-tag>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="报名状态" width="100" align="center" sortable="custom">
              <template #default="{ row }">
                <el-tag :type="getStatusTagType(row.status)" size="small">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="冲突检测" width="100" align="center">
              <template #default="{ row }">
                <el-tooltip v-if="row.hasConflict" content="存在时间冲突" placement="top">
                  <el-icon color="#F56C6C" size="16"><Warning /></el-icon>
                </el-tooltip>
                <el-icon v-else color="#67C23A" size="16"><CircleCheck /></el-icon>
              </template>
            </el-table-column>
            <el-table-column prop="healthStatement" label="健康声明" min-width="150" show-overflow-tooltip>
              <template #default="{ row }">
                <el-tooltip
                  v-if="row.healthStatement"
                  :content="row.healthStatement"
                  placement="top">
                  <div class="health-statement">{{ truncateText(row.healthStatement, 30) }}</div>
                </el-tooltip>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="auditor" label="审核人" width="100" align="center" show-overflow-tooltip>
              <template #default="{ row }">
                {{ row.auditor || '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="报名时间" width="160" align="center" sortable="custom">
              <template #default="{ row }">
                {{ formatDateTime(row.createdAt) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" align="center" fixed="right">
              <template #default="{ row }">
                <el-button-group>
                  <el-tooltip content="查看详情" placement="top">
                    <el-button
                      type="primary"
                      :icon="View"
                      size="small"
                      @click="handleViewDetails(row)">
                    </el-button>
                  </el-tooltip>
                  <el-tooltip v-if="row.status === '待审核'" content="通过" placement="top">
                    <el-button
                      type="success"
                      :icon="Check"
                      size="small"
                      @click="handleAudit(row, '已通过')">
                    </el-button>
                  </el-tooltip>
                  <el-tooltip v-if="row.status === '待审核'" content="驳回" placement="top">
                    <el-button
                      type="danger"
                      :icon="Close"
                      size="small"
                      @click="handleAudit(row, '已驳回')">
                    </el-button>
                  </el-tooltip>
                  <el-tooltip v-if="row.hasConflict" content="查看冲突" placement="top">
                    <el-button
                      type="warning"
                      :icon="Warning"
                      size="small"
                      @click="viewConflictDetails(row)">
                    </el-button>
                  </el-tooltip>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 卡片视图 -->
        <div v-show="viewMode === 'card'" class="card-view">
          <el-row :gutter="20">
            <el-col
              v-for="enrollment in enrollmentList"
              :key="enrollment.id"
              :xs="24"
              :sm="12"
              :md="8"
              :lg="6">
              <el-card class="enrollment-card" shadow="hover">
                <div class="card-header">
                  <div class="student-info">
                    <el-avatar :size="40" :src="enrollment.user?.avatar" icon="UserFilled"></el-avatar>
                    <div class="student-details">
                      <div class="student-name">{{ enrollment.user?.realName || '-' }}</div>
                      <div class="student-meta">{{ enrollment.user?.className || '-' }}</div>
                    </div>
                  </div>
                  <el-tag :type="getStatusTagType(enrollment.status)" size="small">
                    {{ getStatusText(enrollment.status) }}
                  </el-tag>
                </div>

                <div class="card-content">
                  <div class="project-item">
                    <el-icon><Trophy /></el-icon>
                    <span>{{ enrollment.project?.name || '-' }}</span>
                  </div>
                  <div class="detail-item">
                    <span class="label">项目类型:</span>
                    <el-tag size="small" :type="getProjectTypeTagType(enrollment.project?.type)">
                      {{ enrollment.project?.type || '-' }}
                    </el-tag>
                  </div>
                  <div class="detail-item">
                    <span class="label">性别限制:</span>
                    <el-tag size="small" :type="getGenderTagType(enrollment.project?.genderLimit)">
                      {{ getGenderLimitText(enrollment.project?.genderLimit) }}
                    </el-tag>
                  </div>
                  <div class="detail-item">
                    <span class="label">报名时间:</span>
                    <span>{{ formatDateTime(enrollment.createdAt) }}</span>
                  </div>
                  <div v-if="enrollment.hasConflict" class="conflict-warning">
                    <el-icon color="#F56C6C"><Warning /></el-icon>
                    <span>存在时间冲突</span>
                  </div>
                </div>

                <div class="card-actions">
                  <el-button-group>
                    <el-button type="primary" size="small" @click="handleViewDetails(enrollment)">
                      详情
                    </el-button>
                    <el-button
                      v-if="enrollment.status === '待审核'"
                      type="success"
                      size="small"
                      @click="handleAudit(enrollment, '已通过')">
                      通过
                    </el-button>
                    <el-button
                      v-if="enrollment.status === '待审核'"
                      type="danger"
                      size="small"
                      @click="handleAudit(enrollment, '已驳回')">
                      驳回
                    </el-button>
                  </el-button-group>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <!-- 分页控制 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background>
          </el-pagination>
        </div>

        <!-- 批量操作栏 -->
        <div class="batch-operations" v-if="selectedRows.length > 0">
          <div class="batch-info">
            <el-icon><Select /></el-icon>
            <span>已选择 {{ selectedRows.length }} 项</span>
          </div>
          <div class="batch-actions">
            <el-button-group>
              <el-button type="success" @click="handleBatchApprove" :loading="batchLoading">
                <el-icon><Check /></el-icon> 批量通过
              </el-button>
              <el-button type="danger" @click="handleBatchReject" :loading="batchLoading">
                <el-icon><Close /></el-icon> 批量驳回
              </el-button>
              <el-button type="warning" @click="handleBatchExport" :loading="batchLoading">
                <el-icon><Download /></el-icon> 批量导出
              </el-button>
            </el-button-group>
          </div>
        </div>
      </el-card>

      <!-- 详情对话框 -->
      <el-dialog
        v-model="detailDialogVisible"
        title="报名详情"
        width="800px"
        :before-close="handleDetailDialogClose">
        <div v-if="selectedEnrollment" class="enrollment-detail">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="报名ID">{{ selectedEnrollment.id }}</el-descriptions-item>
            <el-descriptions-item label="报名状态">
              <el-tag :type="getStatusTagType(selectedEnrollment.status)">
                {{ getStatusText(selectedEnrollment.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="学生姓名">{{ selectedEnrollment.user?.realName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="学号">{{ selectedEnrollment.user?.studentId || '-' }}</el-descriptions-item>
            <el-descriptions-item label="班级">{{ selectedEnrollment.user?.className || '-' }}</el-descriptions-item>
            <el-descriptions-item label="院系">{{ selectedEnrollment.user?.college || '-' }}</el-descriptions-item>
            <el-descriptions-item label="性别">{{ selectedEnrollment.user?.gender || '-' }}</el-descriptions-item>
            <el-descriptions-item label="年级">{{ selectedEnrollment.user?.grade || '-' }}</el-descriptions-item>
            <el-descriptions-item label="项目名称">{{ selectedEnrollment.project?.name || '-' }}</el-descriptions-item>
            <el-descriptions-item label="项目类型">{{ selectedEnrollment.project?.type || '-' }}</el-descriptions-item>
            <el-descriptions-item label="性别限制">{{ getGenderLimitText(selectedEnrollment.project?.genderLimit) }}</el-descriptions-item>
            <el-descriptions-item label="最大人数">{{ selectedEnrollment.project?.maxPlayers || '-' }}</el-descriptions-item>
            <el-descriptions-item label="报名时间">{{ formatDateTime(selectedEnrollment.createdAt) }}</el-descriptions-item>
            <el-descriptions-item label="审核人">{{ selectedEnrollment.auditor || '-' }}</el-descriptions-item>
            <el-descriptions-item label="健康声明" :span="2">
              <div class="health-statement-full">{{ selectedEnrollment.healthStatement || '-' }}</div>
            </el-descriptions-item>
            <el-descriptions-item v-if="selectedEnrollment.rejectReason" label="驳回原因" :span="2">
              <div class="reject-reason-full">{{ selectedEnrollment.rejectReason }}</div>
            </el-descriptions-item>
            <el-descriptions-item v-if="selectedEnrollment.hasConflict" label="冲突信息" :span="2">
              <div class="conflict-info">
                <el-icon color="#F56C6C"><Warning /></el-icon>
                <span>存在时间冲突，请查看详细信息</span>
              </div>
            </el-descriptions-item>
          </el-descriptions>

          <!-- 冲突详情 -->
          <div v-if="selectedEnrollment.hasConflict && conflictDetails.length > 0" class="conflict-section">
            <el-divider content-position="left">冲突详情</el-divider>
            <el-table :data="conflictDetails" size="small">
              <el-table-column prop="projectName" label="冲突项目" />
              <el-table-column prop="scheduleTime" label="比赛时间" />
              <el-table-column prop="location" label="比赛地点" />
            </el-table>
          </div>
        </div>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="detailDialogVisible = false">关闭</el-button>
            <el-button
              v-if="selectedEnrollment?.status === '待审核'"
              type="success"
              @click="handleAudit(selectedEnrollment, '已通过')">
              通过
            </el-button>
            <el-button
              v-if="selectedEnrollment?.status === '待审核'"
              type="danger"
              @click="handleAudit(selectedEnrollment, '已驳回')">
              驳回
            </el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 驳回对话框 -->
      <el-dialog
        v-model="rejectDialogVisible"
        title="驳回报名"
        width="500px"
        @close="resetRejectForm">
        <el-form
          ref="rejectFormRef"
          :model="rejectForm"
          :rules="rejectFormRules"
          label-width="100px">
          <el-form-item label="学生姓名">
            <el-input v-model="rejectForm.studentName" disabled />
          </el-form-item>
          <el-form-item label="项目名称">
            <el-input v-model="rejectForm.projectName" disabled />
          </el-form-item>
          <el-form-item label="驳回原因" prop="rejectReason">
            <el-input
              v-model="rejectForm.rejectReason"
              type="textarea"
              :rows="4"
              placeholder="请输入驳回原因..."
              maxlength="200"
              show-word-limit />
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="rejectDialogVisible = false">取消</el-button>
            <el-button type="danger" @click="handleConfirmReject" :loading="rejectLoading">
              确认驳回
            </el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 报名设置对话框 -->
      <el-dialog
        v-model="showEnrollmentSettings"
        title="报名设置"
        width="600px"
        @close="resetEnrollmentSettings">
        <el-form
          ref="settingsFormRef"
          :model="enrollmentSettings"
          :rules="settingsRules"
          label-width="120px">
          <el-form-item label="报名开始时间" prop="startTime">
            <el-date-picker
              v-model="enrollmentSettings.startTime"
              type="datetime"
              placeholder="选择开始时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss" />
          </el-form-item>
          <el-form-item label="报名结束时间" prop="endTime">
            <el-date-picker
              v-model="enrollmentSettings.endTime"
              type="datetime"
              placeholder="选择结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss" />
          </el-form-item>
          <el-form-item label="每人最多报名" prop="maxEnrollments">
            <el-input-number
              v-model="enrollmentSettings.maxEnrollments"
              :min="1"
              :max="10"
              placeholder="每人最多报名项目数" />
          </el-form-item>
          <el-form-item label="性别限制" prop="genderLimit">
            <el-radio-group v-model="enrollmentSettings.genderLimit">
              <el-radio label="无">无限制</el-radio>
              <el-radio label="男">仅限男生</el-radio>
              <el-radio label="女">仅限女生</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="年级限制" prop="gradeLimit">
            <el-checkbox-group v-model="enrollmentSettings.gradeLimit">
              <el-checkbox v-for="grade in gradeOptions" :key="grade" :label="grade">
                {{ grade }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="需要健康声明" prop="requireHealthStatement">
            <el-switch v-model="enrollmentSettings.requireHealthStatement" />
          </el-form-item>
          <el-form-item label="自动审核" prop="autoApprove">
            <el-switch v-model="enrollmentSettings.autoApprove" />
            <span class="form-tip">开启后将自动通过符合条件的学生报名</span>
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="showEnrollmentSettings = false">取消</el-button>
            <el-button type="primary" @click="saveEnrollmentSettingsHandler" :loading="settingsLoading">
              保存设置
            </el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 冲突检测结果对话框 -->
      <el-dialog
        v-model="showConflictDialog"
        title="冲突检测结果"
        width="700px">
        <div v-if="conflictList.length > 0" class="conflict-result">
          <el-alert
            title="发现报名冲突"
            type="warning"
            description="以下报名存在时间冲突，请及时处理"
            show-icon
            :closable="false" />
          <el-table :data="conflictList" style="margin-top: 20px">
            <el-table-column prop="studentName" label="学生姓名" />
            <el-table-column prop="project1" label="项目1" />
            <el-table-column prop="time1" label="时间1" />
            <el-table-column prop="project2" label="项目2" />
            <el-table-column prop="time2" label="时间2" />
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="resolveConflict(row)">
                  处理冲突
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-else class="no-conflict">
          <el-empty description="未发现报名冲突" />
        </div>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="showConflictDialog = false">关闭</el-button>
            <el-button type="primary" @click="exportConflictReport" :loading="conflictExportLoading">
              导出冲突报告
            </el-button>
          </div>
        </template>
      </el-dialog>
    </main>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, onBeforeUnmount, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import * as echarts from 'echarts'
import {
  // 导航图标
  Medal, User, Monitor, List, Calendar, Bell, ArrowDown, SwitchButton,
  // 功能图标
  Document, Clock, CircleCheck, CircleClose, Setting, Warning, Download,
  Search, Refresh, Operation, UserFilled, View, Check, Close, Select,
  RefreshRight, Grid, Trophy
} from '@element-plus/icons-vue'
import {
  getEnrollmentPage,
  auditEnrollment,
  batchAuditEnrollments,
  getEnrollmentStatuses,
  exportEnrollments,
  getEnrollmentStats,
  getEnrollmentCharts,
  checkEnrollmentConflicts,
  getEnrollmentSettings,
  saveEnrollmentSettings as saveEnrollmentSettingsAPI
} from '@/api/enrollment'

// 路由和状态管理
const router = useRouter()
const authStore = useAuthStore()

// 响应式数据
const loading = ref(false)
const rejectLoading = ref(false)
const exportLoading = ref(false)
const batchLoading = ref(false)
const settingsLoading = ref(false)
const conflictExportLoading = ref(false)
const enrollmentList = ref([])
const selectedRows = ref([])
const selectedEnrollment = ref(null)
const detailDialogVisible = ref(false)
const rejectDialogVisible = ref(false)
const showEnrollmentSettings = ref(false)
const showConflictDialog = ref(false)
const showAdvancedSearch = ref(false)
const tableSize = ref('default')
const chartSize = ref('default')
const viewMode = ref('table')

// 图表相关
const statusChartRef = ref(null)
const collegeChartRef = ref(null)
const statusChart = ref(null)
const collegeChart = ref(null)
const chartLoading = reactive({
  status: false,
  college: false
})

// 冲突相关数据
const conflictList = ref([])
const conflictDetails = ref([])

// 表格高度
const tableHeight = ref(600)

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 搜索表单
const searchForm = reactive({
  realName: '',
  projectName: '',
  status: '',
  college: '',
  className: '',
  projectType: '',
  gender: '',
  grade: '',
  auditor: '',
  hasConflict: '',
  dateRange: null,
  sortBy: '',
  sortOrder: ''
})

// 驳回表单
const rejectFormRef = ref()
const rejectForm = reactive({
  enrollmentId: null,
  studentName: '',
  projectName: '',
  rejectReason: ''
})

// 驳回表单验证规则
const rejectFormRules = {
  rejectReason: [
    { required: true, message: '请输入驳回原因', trigger: 'blur' },
    { min: 5, max: 200, message: '驳回原因长度应在5-200字符之间', trigger: 'blur' }
  ]
}

// 报名设置
const settingsFormRef = ref()
const enrollmentSettings = reactive({
  startTime: '',
  endTime: '',
  maxEnrollments: 3,
  genderLimit: '无',
  gradeLimit: [],
  requireHealthStatement: true,
  autoApprove: false
})

// 设置表单验证规则
const settingsRules = {
  startTime: [
    { required: true, message: '请选择报名开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择报名结束时间', trigger: 'change' }
  ],
  maxEnrollments: [
    { required: true, message: '请设置每人最多报名数', trigger: 'blur' },
    { type: 'number', min: 1, max: 10, message: '报名数应在1-10之间', trigger: 'blur' }
  ]
}

// 当前用户信息
const currentUser = computed(() => authStore.userInfo || JSON.parse(localStorage.getItem('userInfo')))

// 默认头像URL
const avatarUrl = computed(() => '/img/jstu1.webp')

// 报名状态列表
const enrollmentStatuses = ref([])
const projectTypes = ref([])
const collegeOptions = ref([])
const gradeOptions = ref(['大一', '大二', '大三', '大四'])

// 报名统计数据
const enrollmentStats = reactive({
  total: 0,
  pending: 0,
  approved: 0,
  rejected: 0
})


// 切换高级搜索
const toggleAdvancedSearch = () => {
  showAdvancedSearch.value = !showAdvancedSearch.value
}

// 工具方法
const truncateText = (text, length) => {
  if (!text) return ''
  return text.length > length ? text.substring(0, length) + '...' : text
}

const getStatusTagType = (status) => {
  const statusMap = {
    '待审核': 'warning',
    '已通过': 'success',
    '已驳回': 'danger',
    '已取消': 'info'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    '待审核': '待审核',
    '已通过': '已通过',
    '已驳回': '已驳回',
    '已取消': '已取消'
  }
  return statusMap[status] || status
}

const getProjectTypeTagType = (type) => {
  const typeMap = {
    '径赛': 'primary',
    '田赛': 'success',
    '球类': 'warning',
    '其他': 'info'
  }
  return typeMap[type] || 'info'
}

const getGenderTagType = (gender) => {
  const genderMap = {
    '男': 'primary',
    '女': 'danger',
    '无': 'info'
  }
  return genderMap[gender] || 'info'
}

const getGenderLimitText = (genderLimit) => {
  const genderMap = {
    '男': '仅限男生',
    '女': '仅限女生',
    '无': '无限制'
  }
  return genderMap[genderLimit] || '无限制'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// API调用方法
const fetchEnrollments = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      currentPage: pagination.currentPage,
      pageSize: pagination.pageSize
    }

    // 处理日期范围
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = searchForm.dateRange[0]
      params.endDate = searchForm.dateRange[1]
    }
    delete params.dateRange

    const response = await getEnrollmentPage(pagination.currentPage, pagination.pageSize, params)

    if (response.code === 200) {
      enrollmentList.value = response.data.records || []
      pagination.total = response.data.total || 0

      // 更新统计数据
      updateEnrollmentStats(response.data.records || [])
    } else {
      ElMessage.error(response.message || '获取报名列表失败')
    }
  } catch (error) {
    console.error('获取报名列表失败:', error)
    ElMessage.error('获取报名列表失败')
  } finally {
    loading.value = false
  }
}

// 获取报名统计数据
const fetchEnrollmentStats = async () => {
  try {
    const response = await getEnrollmentStats()
    if (response.code === 200) {
      Object.assign(enrollmentStats, response.data)
    }
  } catch (error) {
    console.error('获取报名统计失败:', error)
  }
}

// 获取报名状态
const fetchEnrollmentStatuses = async () => {
  try {
    const response = await getEnrollmentStatuses()
    if (response.code === 200) {
      enrollmentStatuses.value = response.data || []
    }
  } catch (error) {
    console.error('获取报名状态失败:', error)
  }
}

// 获取院系选项
const fetchCollegeOptions = async () => {
  try {
    // 这里应该调用获取院系列表的API
    // const response = await getColleges()
    // if (response.code === 200) {
    //   collegeOptions.value = response.data || []
    // }
    // 预设院系数据：在实际项目中应从API获取
    collegeOptions.value = ['计算机学院', '信息工程学院', '机械工程学院', '经济管理学院', '外国语学院']
  } catch (error) {
    console.error('获取院系列表失败:', error)
  }
}

// 获取项目类型
const fetchProjectTypes = async () => {
  try {
    // 这里应该调用获取项目类型的API
    // const response = await getProjectTypes()
    // if (response.code === 200) {
    //   projectTypes.value = response.data || []
    // }
    // 预设项目类型：在实际项目中应从API获取
    projectTypes.value = ['径赛', '田赛', '球类', '其他']
  } catch (error) {
    console.error('获取项目类型失败:', error)
  }
}

// 更新统计数据
const updateEnrollmentStats = (data) => {
  enrollmentStats.total = data.length
  enrollmentStats.pending = data.filter(item => item.status === '待审核').length
  enrollmentStats.approved = data.filter(item => item.status === '已通过').length
  enrollmentStats.rejected = data.filter(item => item.status === '已驳回').length
}

// 初始化图表
const initCharts = async () => {
  await nextTick()

  // 初始化状态分布图
  if (statusChartRef.value) {
    statusChart.value = echarts.init(statusChartRef.value)
    updateStatusChart()
  }

  // 初始化院系分布图
  if (collegeChartRef.value) {
    collegeChart.value = echarts.init(collegeChartRef.value)
    updateCollegeChart()
  }
}

// 更新状态分布图
const updateStatusChart = async () => {
  if (!statusChart.value) return

  try {
    chartLoading.status = true
    const response = await getEnrollmentCharts('status')

    if (response.code === 200) {
      const data = response.data
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          bottom: '5%',
          left: 'center'
        },
        series: [
          {
            name: '报名状态',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 20,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: data
          }
        ]
      }
      statusChart.value.setOption(option)
    }
  } catch (error) {
    console.error('获取状态图表数据失败:', error)
  } finally {
    chartLoading.status = false
  }
}

// 更新院系分布图
const updateCollegeChart = async () => {
  if (!collegeChart.value) return

  try {
    chartLoading.college = true
    const response = await getEnrollmentCharts('college')

    if (response.code === 200) {
      const data = response.data
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category',
          data: data.map(item => item.name)
        },
        series: [
          {
            name: '报名人数',
            type: 'bar',
            data: data.map(item => item.value),
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ])
            }
          }
        ]
      }
      collegeChart.value.setOption(option)
    }
  } catch (error) {
    console.error('获取院系图表数据失败:', error)
  } finally {
    chartLoading.college = false
  }
}

// 刷新图表
const refreshChart = (type) => {
  if (type === 'status') {
    updateStatusChart()
  } else if (type === 'college') {
    updateCollegeChart()
  }
}

// 检测冲突
const checkConflicts = async () => {
  try {
    loading.value = true
    const response = await checkEnrollmentConflicts()

    if (response.code === 200) {
      conflictList.value = response.data || []
      showConflictDialog.value = true

      if (conflictList.value.length > 0) {
        ElMessage.warning(`发现 ${conflictList.value.length} 个报名冲突`)
      } else {
        ElMessage.success('未发现报名冲突')
      }
    } else {
      ElMessage.error(response.message || '冲突检测失败')
    }
  } catch (error) {
    console.error('冲突检测失败:', error)
    ElMessage.error('冲突检测失败')
  } finally {
    loading.value = false
  }
}

// 查看冲突详情
const viewConflictDetails = async (enrollment) => {
  try {
    // 这里应该调用获取冲突详情的API
    // const response = await getConflictDetails(enrollment.id)
    // if (response.code === 200) {
    //   conflictDetails.value = response.data || []
    // }

    // 冲突详情模拟数据：在实际项目中应从API获取
    conflictDetails.value = [
      {
        projectName: '100米短跑',
        scheduleTime: '2024-05-15 14:00',
        location: '田径场1号跑道'
      },
      {
        projectName: '跳远',
        scheduleTime: '2024-05-15 14:30',
        location: '田径场沙坑'
      }
    ]

    selectedEnrollment.value = enrollment
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取冲突详情失败:', error)
    ElMessage.error('获取冲突详情失败')
  }
}

// 处理冲突
const resolveConflict = (conflictItem) => {
  // 打开学生详情对话框，让管理员选择保留哪个项目
  ElMessage.info('请在该学生的报名记录中处理冲突')
  showConflictDialog.value = false
  // 可以跳转到该学生的报名详情页
  // 处理冲突：记录冲突信息以供后续处理
  console.log('处理冲突项:', conflictItem)
}

// 导出冲突报告
const exportConflictReport = async () => {
  try {
    conflictExportLoading.value = true
    // 这里应该调用导出冲突报告的API
    ElMessage.success('冲突报告导出成功')
  } catch (error) {
    console.error('导出冲突报告失败:', error)
    ElMessage.error('导出冲突报告失败')
  } finally {
    conflictExportLoading.value = false
  }
}

// 获取报名设置
const fetchEnrollmentSettings = async () => {
  try {
    const response = await getEnrollmentSettings()
    if (response.code === 200) {
      Object.assign(enrollmentSettings, response.data)
    }
  } catch (error) {
    console.error('获取报名设置失败:', error)
  }
}

// 保存报名设置
const saveEnrollmentSettingsHandler = async () => {
  if (!settingsFormRef.value) return

  await settingsFormRef.value.validate(async (valid) => {
    if (valid) {
      settingsLoading.value = true
      try {
        const response = await saveEnrollmentSettingsAPI(enrollmentSettings)
        if (response.code === 200) {
          ElMessage.success('报名设置保存成功')
          showEnrollmentSettings.value = false
        } else {
          ElMessage.error(response.message || '保存设置失败')
        }
      } catch (error) {
        console.error('保存报名设置失败:', error)
        ElMessage.error('保存报名设置失败')
      } finally {
        settingsLoading.value = false
      }
    }
  })
}

// 重置报名设置
const resetEnrollmentSettings = () => {
  if (settingsFormRef.value) {
    settingsFormRef.value.resetFields()
  }
  fetchEnrollmentSettings()
}

// 事件处理方法
const handleSearch = () => {
  pagination.currentPage = 1
  fetchEnrollments()
}

const handleReset = () => {
  Object.assign(searchForm, {
    realName: '',
    projectName: '',
    status: '',
    college: '',
    className: '',
    projectType: '',
    gender: '',
    grade: '',
    auditor: '',
    hasConflict: '',
    dateRange: null,
    sortBy: '',
    sortOrder: ''
  })
  handleSearch()
}

const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  fetchEnrollments()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchEnrollments()
}

const handleSortChange = ({ prop, order }) => {
  searchForm.sortBy = prop
  searchForm.sortOrder = order === 'ascending' ? 'asc' : order === 'descending' ? 'desc' : ''
  fetchEnrollments()
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const handleViewDetails = (enrollment) => {
  selectedEnrollment.value = enrollment
  detailDialogVisible.value = true
}

const handleDetailDialogClose = () => {
  detailDialogVisible.value = false
  selectedEnrollment.value = null
  conflictDetails.value = []
}

const handleAudit = async (enrollment, status) => {
  if (status === '已通过') {
    try {
      await ElMessageBox.confirm(
        `确定要通过 ${enrollment.user?.realName} 的报名申请吗？`,
        '确认通过',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success'
        }
      )

      const response = await auditEnrollment(enrollment.id, status)
      if (response.code === 200) {
        ElMessage.success('审核通过成功')
        fetchEnrollments()
        fetchEnrollmentStats()
        refreshChart('status')
      } else {
        ElMessage.error(response.message || '审核失败')
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error('审核失败:', error)
        ElMessage.error('审核失败')
      }
    }
  } else if (status === '已驳回') {
    rejectForm.enrollmentId = enrollment.id
    rejectForm.studentName = enrollment.user?.realName || ''
    rejectForm.projectName = enrollment.project?.name || ''
    rejectForm.rejectReason = ''
    rejectDialogVisible.value = true
  }
}

const handleConfirmReject = async () => {
  try {
    await rejectFormRef.value.validate()

    rejectLoading.value = true

    const response = await auditEnrollment(
      rejectForm.enrollmentId,
      '已驳回',
      rejectForm.rejectReason
    )

    if (response.code === 200) {
      ElMessage.success('驳回成功')
      rejectDialogVisible.value = false
      fetchEnrollments()
      fetchEnrollmentStats()
      refreshChart('status')
    } else {
      ElMessage.error(response.message || '驳回失败')
    }
  } catch (error) {
    if (error.name !== 'ElFormValidateError') {
      console.error('驳回失败:', error)
      ElMessage.error('驳回失败')
    }
  } finally {
    rejectLoading.value = false
  }
}

const handleBatchApprove = async () => {
  const pendingEnrollments = selectedRows.value.filter(row => row.status === '待审核')

  if (pendingEnrollments.length === 0) {
    ElMessage.warning('请选择待审核的报名记录')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要通过选中的 ${pendingEnrollments.length} 条报名申请吗？`,
      '确认批量通过',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }
    )

    batchLoading.value = true
    const enrollmentIds = pendingEnrollments.map(item => item.id)
    const response = await batchAuditEnrollments(enrollmentIds, '已通过')

    if (response.code === 200) {
      ElMessage.success('批量审核通过成功')
      fetchEnrollments()
      fetchEnrollmentStats()
      refreshChart('status')
      selectedRows.value = []
    } else {
      ElMessage.error(response.message || '批量审核失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量审核失败:', error)
      ElMessage.error('批量审核失败')
    }
  } finally {
    batchLoading.value = false
  }
}

const handleBatchReject = async () => {
  const pendingEnrollments = selectedRows.value.filter(row => row.status === '待审核')

  if (pendingEnrollments.length === 0) {
    ElMessage.warning('请选择待审核的报名记录')
    return
  }

  try {
    const { value: rejectReason } = await ElMessageBox.prompt(
      `请输入驳回原因（将应用于选中的 ${pendingEnrollments.length} 条记录）`,
      '批量驳回',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^.{5,200}$/,
        inputErrorMessage: '驳回原因长度应在5-200字符之间',
        inputType: 'textarea'
      }
    )

    batchLoading.value = true
    const enrollmentIds = pendingEnrollments.map(item => item.id)
    const response = await batchAuditEnrollments(enrollmentIds, '已驳回', rejectReason)

    if (response.code === 200) {
      ElMessage.success('批量驳回成功')
      fetchEnrollments()
      fetchEnrollmentStats()
      refreshChart('status')
      selectedRows.value = []
    } else {
      ElMessage.error(response.message || '批量驳回失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量驳回失败:', error)
      ElMessage.error('批量驳回失败')
    }
  } finally {
    batchLoading.value = false
  }
}

// 导出功能
const handleExport = async () => {
  try {
    exportLoading.value = true
    const params = { ...searchForm }

    // 处理日期范围
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = searchForm.dateRange[0]
      params.endDate = searchForm.dateRange[1]
    }
    delete params.dateRange

    const response = await exportEnrollments(params)

    // 创建下载链接
    const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `报名信息_${new Date().toLocaleDateString('zh-CN')}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    exportLoading.value = false
  }
}

const handleBatchExport = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要导出的报名记录')
    return
  }

  try {
    batchLoading.value = true
    const enrollmentIds = selectedRows.value.map(item => item.id)

    // 这里应该调用批量导出API
    // const response = await batchExportEnrollments(enrollmentIds)
    // 准备导出报名数据：获取选中的报名ID列表
    console.log('准备导出的报名ID列表:', enrollmentIds)

    ElMessage.success('批量导出成功')
    selectedRows.value = []
  } catch (error) {
    console.error('批量导出失败:', error)
    ElMessage.error('批量导出失败')
  } finally {
    batchLoading.value = false
  }
}

const resetRejectForm = () => {
  rejectFormRef.value?.resetFields()
  Object.assign(rejectForm, {
    enrollmentId: null,
    studentName: '',
    projectName: '',
    rejectReason: ''
  })
}

// 退出登录
const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 使用Pinia store进行登出
    await authStore.logout()
    // 跳转到登录页
    router.push('/login')
  })
}

// 导航到指定路径
const navigateTo = (path) => {
  router.push(path)
}

// 窗口大小变化处理
const handleResize = () => {
  // 重新调整图表大小
  if (statusChart.value) {
    statusChart.value.resize()
  }
  if (collegeChart.value) {
    collegeChart.value.resize()
  }
}

// 初始化数据
const initData = async () => {
  await Promise.all([
    fetchEnrollments(),
    fetchEnrollmentStats(),
    fetchEnrollmentStatuses(),
    fetchCollegeOptions(),
    fetchProjectTypes(),
    fetchEnrollmentSettings()
  ])

  // 初始化图表
  initCharts()
}

// 生命周期钩子
onMounted(() => {
  window.addEventListener('resize', handleResize)

  // 初始化数据
  initData()
})

// 组件卸载时清理
onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)

  // 销毁图表实例
  if (statusChart.value) {
    statusChart.value.dispose()
  }
  if (collegeChart.value) {
    collegeChart.value.dispose()
  }
})
</script>

<style scoped>
/* 基础样式 */
* {
  font-family: 'PingFang SC', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  box-sizing: border-box;
}

/* 全局变量 */
:root {
  --primary-color: #2C5AA0;
  --primary-light: #E8EFF9;
  --primary-dark: #1E3D73;
  --success-color: #67C23A;
  --warning-color: #E6A23C;
  --danger-color: #F56C6C;
  --info-color: #909399;
  --text-primary: #303133;
  --text-regular: #606266;
  --text-secondary: #909399;
  --text-placeholder: #C0C4CC;
  --border-light: #EBEEF5;
  --border-base: #DCDFE6;
  --border-lighter: #F2F6FC;
  --background-base: #F5F7FA;
  --background-light: #FAFAFA;
}

/* 容器布局 */
.app-container {
  display: grid;
  grid-template-columns: 240px 1fr;
  grid-template-rows: 64px 1fr;
  min-height: 100vh;
  background-color: var(--background-base);
}

/* 顶部导航栏 */
.header {
  grid-column: 1 / -1;
  background-color: var(--primary-color);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 100;
}

.logo {
  font-size: 20px;
  font-weight: 600;
  color: white;
  display: flex;
  align-items: center;
  gap: 12px;
  letter-spacing: 0.5px;
}

.flex-grow {
  flex-grow: 1;
}

/* 用户信息区域 */
.user-info {
  display: flex;
  align-items: center;
}

.user-avatar {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 6px;
  transition: background-color 0.3s;
}

.user-avatar:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.username {
  color: white;
  font-size: 14px;
  font-weight: 500;
}

/* 左侧导航栏 */
.sidebar {
  background-color: white;
  padding: 16px 0;
  border-right: 1px solid var(--border-light);
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.05);
  overflow-y: auto;
}

.menu-item {
  padding: 14px 24px;
  color: var(--text-regular);
  display: flex;
  align-items: center;
  gap: 12px;
  transition: all 0.3s ease;
  cursor: pointer;
  font-weight: 500;
  position: relative;
}

.menu-item:hover {
  background-color: var(--primary-light);
  color: var(--primary-color);
}

.menu-item.active {
  background-color: var(--primary-light);
  color: var(--primary-color);
}

.menu-item.active::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  background-color: var(--primary-color);
}

.menu-item span {
  font-size: 15px;
}

/* 主内容区 */
.content {
  padding: 24px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 页面标题区域 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  flex-wrap: wrap;
  gap: 16px;
}

.page-title h1 {
  font-size: 28px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 8px 0;
}

.page-desc {
  font-size: 14px;
  color: var(--text-secondary);
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

/* 统计行 */
.stats-row {
  margin-bottom: 0;
}

/* 图表行 */
.chart-row {
  margin-bottom: 0;
}

/* 统计卡片 */
.stats-card {
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
}

.stats-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.stats-content {
  position: relative;
  z-index: 2;
}

.stats-number {
  font-size: 32px;
  font-weight: bold;
  color: var(--text-primary);
  line-height: 1;
}

.stats-label {
  font-size: 14px;
  color: var(--text-secondary);
  margin-top: 8px;
}

.stats-icon {
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 48px;
  opacity: 0.2;
  z-index: 1;
}

/* 图表卡片 */
.chart-card {
  height: 350px;
}

.chart-card :deep(.el-card__body) {
  height: calc(100% - 57px);
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  width: 100%;
  height: 100%;
}

/* 搜索卡片 */
.search-card {
  margin-bottom: 0;
}

.search-card :deep(.el-card__body) {
  padding: 24px;
}

.advanced-search {
  margin-top: 20px;
}

/* 表格卡片 */
.table-card {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.table-card :deep(.el-card__body) {
  padding: 0;
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* 表格工具栏 */
.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid var(--border-light);
}

.table-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
}

.table-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.view-switch {
  margin-right: 12px;
}

/* 表格视图 */
.table-view {
  flex: 1;
}

:deep(.el-table) {
  flex: 1;
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: var(--background-light) !important;
  color: var(--text-primary);
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table .el-table__row:hover > td) {
  background-color: var(--primary-light);
}

/* 卡片视图 */
.card-view {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.enrollment-card {
  margin-bottom: 20px;
  transition: all 0.3s ease;
}

.enrollment-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.enrollment-card :deep(.el-card__body) {
  padding: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.student-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.student-details {
  flex: 1;
}

.student-name {
  font-weight: 600;
  color: var(--text-primary);
  font-size: 16px;
}

.student-meta {
  font-size: 12px;
  color: var(--text-secondary);
  margin-top: 2px;
}

.card-content {
  margin-bottom: 16px;
}

.project-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  font-weight: 500;
  color: var(--text-primary);
}

.detail-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
}

.detail-item .label {
  color: var(--text-secondary);
}

.conflict-warning {
  display: flex;
  align-items: center;
  gap: 6px;
  color: var(--danger-color);
  font-size: 12px;
  margin-top: 8px;
}

.card-actions {
  display: flex;
  justify-content: center;
}

/* 用户信息样式 */
.user-info {
  line-height: 1.4;
}

.user-name {
  font-weight: bold;
  color: var(--text-primary);
}

.user-details {
  display: flex;
  gap: 6px;
  margin-top: 4px;
}

/* 项目信息样式 */
.project-info {
  line-height: 1.4;
}

.project-name {
  font-weight: bold;
  color: var(--text-primary);
  margin-bottom: 4px;
}

.project-details {
  display: flex;
  gap: 6px;
}

/* 健康声明和驳回原因样式 */
.health-statement,
.reject-reason {
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.health-statement-full,
.reject-reason-full {
  max-height: 100px;
  overflow-y: auto;
  line-height: 1.5;
}

/* 冲突信息样式 */
.conflict-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--danger-color);
}

.conflict-section {
  margin-top: 20px;
}

/* 冲突结果样式 */
.conflict-result {
  margin-top: 16px;
}

.no-conflict {
  padding: 40px 0;
}

/* 表单提示 */
.form-tip {
  font-size: 12px;
  color: var(--text-secondary);
  margin-left: 8px;
}

/* 分页容器 */
.pagination-container {
  padding: 16px 24px;
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid var(--border-light);
}

/* 批量操作栏 */
.batch-operations {
  padding: 16px 24px;
  background-color: var(--primary-light);
  border-top: 1px solid var(--border-light);
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.batch-info {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: var(--primary-color);
}

.batch-actions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

/* 对话框样式 */
:deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  background-color: var(--primary-color);
  color: white;
  padding: 20px 24px;
}

:deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid var(--border-light);
}

/* 报名详情样式 */
.enrollment-detail {
  padding: 8px 0;
}

.dialog-footer {
  text-align: right;
}

/* 表单样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: var(--text-primary);
}

:deep(.el-input__inner) {
  border-radius: 4px;
}

:deep(.el-select .el-input .el-input__inner) {
  border-radius: 4px;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
}

:deep(.el-descriptions__content) {
  color: var(--text-regular);
}

/* 按钮激活状态 */
:deep(.el-button.is-active) {
  background-color: var(--primary-color);
  border-color: var(--primary-color);
  color: white;
}

/* 表格操作按钮组 */
:deep(.el-button-group .el-button) {
  margin-left: 0;
}

:deep(.el-button-group .el-button + .el-button) {
  margin-left: 1px;
}

/* 标签样式 */
.el-tag {
  margin: 2px;
}

/* 消息提示样式 */
:deep(.el-message) {
  border-radius: 4px;
}

:deep(.el-message-box) {
  border-radius: 8px;
}


/* 动画效果 */
.el-fade-in-enter-active,
.el-fade-in-leave-active {
  transition: opacity 0.3s ease;
}

.el-fade-in-enter-from,
.el-fade-in-leave-to {
  opacity: 0;
}

.el-zoom-in-enter-active,
.el-zoom-in-leave-active {
  transition: all 0.3s ease;
}

.el-zoom-in-enter-from,
.el-zoom-in-leave-to {
  transform: scale(0.9);
  opacity: 0;
}

/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: var(--background-light);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: var(--border-base);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: var(--text-placeholder);
}
</style>